package com.sikaryofficial.backend.annotation;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.sikaryofficial.backend.utils.LikesDataFormatUtil;

import java.io.IOException;
import java.util.Objects;
/**
 * @author : qinjinyuan
 * @desc : 点赞数据格式化
 * @date : 2023/12/06 20:08
 */
public class LikesDataFormatSerialize extends JsonSerializer implements ContextualSerializer {

    @Override
    public void serialize(Object objValue, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (Objects.isNull(objValue)) {
            jsonGenerator.writeString("0");
            return;
        }
        Integer value = (Integer) objValue;
        jsonGenerator.writeString(LikesDataFormatUtil.formatNumber(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (Objects.nonNull(beanProperty)) {
            if (Objects.equals(beanProperty.getType().getRawClass(), Integer.class)) {
                LikesDataFormat anno = beanProperty.getAnnotation(LikesDataFormat.class);
                if (Objects.isNull(anno)) {
                    anno = beanProperty.getContextAnnotation(LikesDataFormat.class);
                }
                if (Objects.nonNull(anno)) {
                    return new LikesDataFormatSerialize();
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(null);
    }
}